/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hu.kovacsp.scala.discovery.jdbc

import com.weiglewilczek.slf4s.Logging
import java.sql.DriverManager
import org.apache.commons.dbcp.ConnectionFactory
import org.apache.commons.dbcp.DriverManagerConnectionFactory
import org.apache.commons.dbcp.PoolableConnectionFactory
import org.apache.commons.dbcp.PoolingDriver
import org.apache.commons.pool.ObjectPool
import org.apache.commons.pool.impl.GenericObjectPool

class ManualPoolingDriver(driverClassName: String, poolName: String) extends Logging{
  System.out.println("Loading underlying JDBC driver.");
  try {
    Class.forName(driverClassName);
  } catch {
    case e: ClassNotFoundException =>
  }

  def setupDriver(connectURI: String): Unit = {
    //
    // First, we'll need a ObjectPool that serves as the
    // actual pool of connections.
    //
    // We'll use a GenericObjectPool instance, although
    // any ObjectPool implementation will suffice.
    //
    val connectionPool: ObjectPool = new GenericObjectPool(null)

    //
    // Next, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    val connectionFactory: ConnectionFactory =
      new DriverManagerConnectionFactory(connectURI, null)

    //
    // Now we'll create the PoolableConnectionFactory, which wraps
    // the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    //
    val poolableConnectionFactory: PoolableConnectionFactory  =
      new PoolableConnectionFactory(connectionFactory, connectionPool,null,null,false,true)

    //
    // Finally, we create the PoolingDriver itself...
    //
    Class.forName("org.apache.commons.dbcp.PoolingDriver")
    val driver: PoolingDriver =
      DriverManager.getDriver("jdbc:apache:commons:dbcp:").asInstanceOf[PoolingDriver]
    //
    // ...and register our pool with it.
    //
    driver.registerPool("example", connectionPool);
    //
    // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
    // to access our pool of Connections.
    //
  }

  def printDriverStats(): Unit = {
        val driver: PoolingDriver =
          DriverManager.getDriver("jdbc:apache:commons:dbcp:").asInstanceOf[PoolingDriver]
        val connectionPool: ObjectPool = driver.getConnectionPool("example");

        logger info("NumActive: " + connectionPool.getNumActive());
        logger info("NumIdle: " + connectionPool.getNumIdle());
    }

    def shutdownDriver(): Unit = {
        val driver: PoolingDriver =
          DriverManager.getDriver("jdbc:apache:commons:dbcp:").asInstanceOf[PoolingDriver]
        driver.closePool("example");
    }

}
